package com.hefantv.admin.controller.${webPackageName};

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hefantv.admin.common.api.constants.IConstants;
import com.hefantv.admin.common.api.util.HttpClient4Util;
import com.hefantv.admin.common.api.util.Json;
import com.hefantv.admin.common.api.util.StringUtil;
import com.hefantv.admin.common.tag.Pager;
import com.hefantv.admin.common.tag.PagerHelper;
import com.hefantv.admin.controller.BaseController;
import com.hefantv.admin.domain.model.${objectName}Model;
import com.hefantv.admin.domain.request.HttpDataParam;
import com.hefantv.admin.domain.request.HttpQueryParam;
import com.hefantv.admin.domain.request.QueryCondition;
import com.hefantv.admin.domain.response.HttpResponseData;
import com.hefantv.admin.domain.response.ResponseData;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* ${description}
* Created by AUTO on ${nowDate?string("yyyy/MM/dd")}.
*/
@Controller
@RequestMapping("${objectNameLower}")
public class ${objectName}Controller extends BaseController{

    private static final Logger logger = Logger.getLogger(${objectName}Controller.class);

    /**
     * 查询列表
     * @param requestModel 请求参数
     * @param ph 分页参数
     * @return
     */
    @RequestMapping("/queryList")
    public ModelAndView queryList(${objectName}Model requestModel, PagerHelper ph){
        ModelAndView mv = new ModelAndView();
        try {
            ResponseData data = getListData(requestModel,ph);
            if(data.getCode() == IConstants.HTTP_SUCCESS){
                Pager pager = new Pager(ph.getCurrent(),ph.getSize(),ph.getSortColumn(),ph.getSortOrder());
                pager.setTotal(data.getTotalCount());
                List<${objectName}Model> list = JSON.parseArray(data.getData().toString(), ${objectName}Model.class);
                mv.addObject("list", list);
                mv.addObject("page", pager);
                mv.addObject("requestModel",requestModel);
            }else{
                logger.error(data.getHttpMsg());
            }
        } catch (Exception e) {
            logger.error("${objectNameLower}/queryList error--param:程序异常:"
                    + e.toString());
        }
        mv.setViewName("/${webPackageName}/${objectNameLower}/${objectNameLower}_list");
        return mv;
    }

    /**
     * 跳转到新增页面
     * @return
     */
    @RequestMapping("/goAdd")
    public ModelAndView goAdd(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/${webPackageName}/${objectNameLower}/${objectNameLower}_add");
        return mv;
    }

    /**
     * 新增
     * @param model
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public Json save(${objectName}Model model){
        Json json = new Json();
        try {
            HttpDataParam<${objectName}Model> httpDataParam = new HttpDataParam<${objectName}Model>();
            List<${objectName}Model> list = new ArrayList<${objectName}Model>();
            list.add(model);
            httpDataParam.setObjects(list);
            httpDataParam.setSource("后台管理");
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put(IConstants.PARAM_DATA, JSON.toJSONString(httpDataParam));
            //请求服务端做新增操作
            String retJson = HttpClient4Util.post(IConstants.${httpUrlName}_SERVER_INSERT_URL,paramMap);
            ResponseData response = JSON.parseObject(retJson,ResponseData.class);
            //判断是否操作成功
            if(response.getCode() == IConstants.HTTP_SUCCESS){
                json.setSuccess(true);
            }else{
                json.setMsg(response.getHttpMsg());
            }

        } catch (Exception e) {
            logger.error("save error--param:" + model +"程序异常:"
                    + e.toString());
            json.setMsg(e.toString());
        }
        return json;
    }

    /**
     * 跳转到编辑页面
     * @return
     */
    @RequestMapping("/goEdit")
    public ModelAndView goEdit(Long id){
        ModelAndView mv = new ModelAndView();
        ${objectName}Model model;
        try {
            model = getDataById(id);
        } catch (Exception e) {
            logger.error("${objectNameLower}/goEdit error--param:程序异常:"
                    + e.toString());
            model = new ${objectName}Model();
        }
        mv.addObject("model",model);
        mv.setViewName("/${webPackageName}/${objectNameLower}/${objectNameLower}_edit");
        return mv;
    }

    /**
     * 修改
     * @param model
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public Json update(${objectName}Model model){
        Json json = new Json();
        try {
            HttpDataParam<${objectName}Model> httpDataParam = new HttpDataParam<${objectName}Model>();
            List<${objectName}Model> list = new ArrayList<${objectName}Model>();
            list.add(model);
            httpDataParam.setObjects(list);
            httpDataParam.setSource("后台管理");
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put(IConstants.PARAM_DATA, JSON.toJSONString(httpDataParam));
            String retJson = HttpClient4Util.post(IConstants.${httpUrlName}_SERVER_UPDATE_URL,paramMap);
            ResponseData response = JSON.parseObject(retJson,ResponseData.class);
            //判断是否操作成功
            if(response.getCode() == IConstants.HTTP_SUCCESS){
                json.setSuccess(true);
            }else{
                json.setMsg(response.getMsg());
            }
        } catch (Exception e) {
            logger.error("update error--param:" + model +"程序异常:"
                    + e.toString());
            json.setMsg(e.toString());
        }
        return json;
    }

    /**
     * 删除
     * @param model
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Json delete(${objectName}Model model){
        Json json = new Json();
        try {
            HttpDataParam<${objectName}Model> httpDataParam = new HttpDataParam<${objectName}Model>();
            List<${objectName}Model> list = new ArrayList<${objectName}Model>();
            list.add(model);
            httpDataParam.setObjects(list);
            httpDataParam.setSource("后台管理");
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put(IConstants.PARAM_DATA, JSON.toJSONString(httpDataParam));
            String retJson = HttpClient4Util.post(IConstants.${httpUrlName}_SERVER_DELETE_URL,paramMap);
            ResponseData response = JSON.parseObject(retJson,ResponseData.class);
            //判断是否操作成功
            if(response.getCode() == IConstants.HTTP_SUCCESS){
                json.setSuccess(true);
            }else{
                json.setMsg(response.getMsg());
            }
        } catch (Exception e) {
            logger.error("delete error--param:" + model +"程序异常:"
                    + e.toString());
            json.setMsg(e.toString());
        }
        return json;
    }

    /**
     * 请求服务端查询数据
     * @param requestModel 请求参数
     * @param ph 分页
     * @return
     * @throws Exception
     */
    private ResponseData getListData(${objectName}Model requestModel, PagerHelper ph) throws Exception{
        //查询条件集
        List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();

        //请在下面构建查询条件, id查询为示例,不使用请删除
        if(requestModel.getId() != null){
            queryConditions.add(getQueryCondition("id",requestModel.getId(), OperatorTypeEnum.eq));
        }

        //
        HttpQueryParam httpQueryParam = new HttpQueryParam();
        //是否返回总页数:1是
        httpQueryParam.setNeedTotal(1);
        //查询的字段集
        httpQueryParam.setFields(IConstants.${httpUrlName}_SERVER_FIELDS);
        //查询起始位置
        httpQueryParam.setStart(ph.getStart());
        //查询数量
        httpQueryParam.setSize(ph.getSize());

        //排序
        if(StringUtil.isBlank(ph.getSortColumn())){
            httpQueryParam.setOrderColumn("id");
            httpQueryParam.setOrderDirection(1);
        }else{
            httpQueryParam.setOrderColumn(ph.getSortColumn());
            httpQueryParam.setOrderDirection(ph.getSortOrder());
        }
        httpQueryParam.setQueryConditions(queryConditions);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(IConstants.PARAM_DATA, JSON.toJSONString(httpQueryParam));
        String retJson = HttpClient4Util.post(IConstants.${httpUrlName}_SERVER_QUERY_URL,paramMap);
        return JSON.parseObject(retJson,ResponseData.class);
    }

    /**
     * 根据ID查询单条数据
     * @param id
     * @return
     * @throws Exception
     */
    private ${objectName}Model getDataById(Long id) throws Exception {
        List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
        //根据ID删除数据
        queryConditions.add(getQueryCondition("id",id,OperatorTypeEnum.eq));

        HttpQueryParam httpQueryParam = new HttpQueryParam();
        httpQueryParam.setFields(IConstants.${httpUrlName}_SERVER_FIELDS);
        httpQueryParam.setQueryConditions(queryConditions);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(IConstants.PARAM_DATA, JSON.toJSONString(httpQueryParam));
        String retJson = HttpClient4Util.post(IConstants.${httpUrlName}_SERVER_QUERY_URL,paramMap);

        ResponseData data = JSON.parseObject(retJson,ResponseData.class);
        if(data.getCode() == IConstants.HTTP_SUCCESS){
            HttpResponseData<List<${objectName}Model>> httpResponseData = JSON.parseObject(retJson,new TypeReference<HttpResponseData<List<${objectName}Model>>>(){});
            List<${objectName}Model> list = httpResponseData.getData();
            if(list.size()==1){
                return list.get(0);
            }else if(list.size()>1){
                logger.error("数据出现异常,发现"+list.size()+"条数据:"+JSON.toJSONString(list));
            }
        }else{
            logger.error(data.getHttpMsg());
        }
        return new ${objectName}Model();
    }
}